package system

import (
	"context"
	"github.com/samber/lo"
	"private-domain-overseas-service/admin/business/api/internal/repository/system"
	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"
	"private-domain-overseas-service/tools/ent"
	"private-domain-overseas-service/tools/ent/hzsystemconfig"
	"private-domain-overseas-service/tools/ent/predicate"
	"time"

	"github.com/zeromicro/go-zero/core/logx"
)

type SystemConfigListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewSystemConfigListLogic - 系统配置列表
func NewSystemConfigListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SystemConfigListLogic {
	return &SystemConfigListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SystemConfigListLogic) SystemConfigList(req *types.SystemConfigListRequest) (resp *types.SystemConfigListResponse, err error) {
	// 创建实例
	configDao := system.NewSystemConfigDao(l.ctx, l.svcCtx)

	// 查询配置信息
	configConditions := make([]predicate.HzSystemConfig, 0)
	configConditions = append(configConditions, hzsystemconfig.DeleteAtIsNil())
	if req.Id != 0 {
		configConditions = append(configConditions, hzsystemconfig.IDEQ(int(req.Id)))
	}
	if len(req.SysteKey) > 0 {
		configConditions = append(configConditions, hzsystemconfig.SystemKeyEQ(req.SysteKey))
	}
	if len(req.Keyword) > 0 {
		configConditions = append(configConditions, hzsystemconfig.Or(
			hzsystemconfig.SystemValue(req.Keyword),
			hzsystemconfig.SystemDescription(req.Keyword),
		))
	}
	configList, verCount, err := configDao.SystemConfigConditionsAllByPage(configConditions, req.Current, req.PageSize)
	if err != nil {
		return nil, err
	}

	// 组装数据
	list := lo.Map(configList, func(item *ent.HzSystemConfig, _ int) *types.SystemConfigInfo {
		return &types.SystemConfigInfo{
			Id:                int64(item.ID),
			SystemKey:         item.SystemKey,
			SystemValue:       item.SystemValue,
			SystemDescription: item.SystemDescription,
			CreatedAt:         time.Unix(item.CreatedAt, 0).Format(time.DateTime),
			UpdateAt:          time.Unix(item.UpdateAt, 0).Format(time.DateTime),
		}
	})

	// 返回数据
	resp = &types.SystemConfigListResponse{
		Page: &types.PageResponse{
			Total:           verCount,
			PageSize:        int64(len(list)),
			RequestPageSize: req.PageSize,
			Current:         req.Current,
		},
		List: list,
	}

	return resp, nil
}
